package com.bhs.sansong.ui.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bhs.sansong.R;
import com.bhs.sansong.adapter.FragmentAdapter;
import com.bhs.sansong.adapter.MenuAdapter;
import com.bhs.sansong.base.BaseBean;
import com.bhs.sansong.base.BaseFragment;
import com.bhs.sansong.base.Constants;
import com.bhs.sansong.bean.ActivityBean;
import com.bhs.sansong.bean.AdvancePayment;
import com.bhs.sansong.bean.AdvertisingBean;
import com.bhs.sansong.bean.CouponSearchBean;
import com.bhs.sansong.bean.MenuBean;
import com.bhs.sansong.bean.Permission;
import com.bhs.sansong.bean.UserInfo;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.dialog.DiscountCouponDialog;
import com.bhs.sansong.ui.dialog.MyClickListener2;
import com.bhs.sansong.ui.dialog.RedPacketDialog;
import com.bhs.sansong.ui.discountCoupon.CouponCollectionCenterActivity;
import com.bhs.sansong.ui.findLogistics.CompanyDetailsActivity;
import com.bhs.sansong.ui.findLogistics.SearchLogisticsFragment;
import com.bhs.sansong.ui.order.DispatchAndCollectActivity;
import com.bhs.sansong.ui.order.EnquiryOrderActivity;
import com.bhs.sansong.ui.order.LogisticsTrackActivity;
import com.bhs.sansong.ui.order.OrderDetailsActivity;
import com.bhs.sansong.ui.order.OrderSearchActivity;
import com.bhs.sansong.ui.orderDispose.AbnormalOrderActivity;
import com.bhs.sansong.ui.other.DataBoardActivity;
import com.bhs.sansong.ui.shipments.SelectAddressFragment;
import com.bhs.sansong.utils.LocationUtils;
import com.bhs.sansong.utils.LogUtils;
import com.bhs.sansong.utils.MyUtils;
import com.bhs.sansong.utils.SharedPreferencesUtils;
import com.bhs.sansong.view.AutoScrollViewPager;
import com.bhs.sansong.view.BannerIndicator;
import com.bhs.sansong.view.SelectedFont;
import com.bhs.sansong.view.ViewPagerAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.journeyapps.barcodescanner.ScanContract;
import com.journeyapps.barcodescanner.ScanOptions;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

/**
 * 首页
 */
public class SanSongFragment extends BaseFragment implements View.OnClickListener, NetCallBack, AMapLocationListener {

    private TabLayout mTabLayout;
    private ViewPager2 mViewPage;
    private RecyclerView mRvMenu;
    private MenuAdapter menuAdapter;
    private AutoScrollViewPager mVpCarousel;
    private BannerIndicator mIndicator;
    private TextView mTvCity;
    private final LocationUtils locationUtils = new LocationUtils();
    private String city;

    public static SanSongFragment newInstance() {
        return new SanSongFragment();
    }

    @Override
    public int initLayout() {
        return R.layout.fragment_san_song;
    }

    @Override
    public void initView(View root) {
        EventBus.getDefault().register(this);
        root.findViewById(R.id.fl_search).setOnClickListener(this);
        root.findViewById(R.id.fl_scan).setOnClickListener(this);
        mTabLayout = root.findViewById(R.id.tabLayout);
        mViewPage = root.findViewById(R.id.view_page);
        mRvMenu = root.findViewById(R.id.rv_menu);
        mVpCarousel = root.findViewById(R.id.vp_carousel);
        mIndicator = root.findViewById(R.id.indicator);
        List<MenuBean> mList = new ArrayList<>();
        mList.add(new MenuBean("领券中心", R.mipmap.ic_coupon));
        mList.add(new MenuBean("异常订单", R.mipmap.ic_abnormal_order));
        mList.add(new MenuBean("询价列表", R.mipmap.ic_inquiry_list));
        mList.add(new MenuBean("数据看板", R.mipmap.ic_data_board));
        menuAdapter = new MenuAdapter(R.layout.item_menu, mList);
        mRvMenu.setAdapter(menuAdapter);
        mRvMenu.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mList.get(position).getMenuName().equals("询价列表")) {
                    startActivity(new Intent(getActivity(), EnquiryOrderActivity.class));
                } else if (mList.get(position).getMenuName().equals("领券中心")) {
                    startActivity(new Intent(getActivity(), CouponCollectionCenterActivity.class));
                } else if (mList.get(position).getMenuName().equals("异常订单")) {
                    startActivity(new Intent(getActivity(), AbnormalOrderActivity.class));
                } else if (mList.get(position).getMenuName().equals("数据看板")) {
                    startActivity(new Intent(getActivity(), DataBoardActivity.class));
                }
            }
        });
        mTvCity = root.findViewById(R.id.tv_city);
        mTvCity.setOnClickListener(this);
    }

    @Override
    public void initData() {
        //禁止滑动
        mViewPage.setUserInputEnabled(false);
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        //tab切换时候的字体设置
        mTabLayout.addOnTabSelectedListener(new SelectedFont(activity));
        ArrayList<BaseFragment> fragments = new ArrayList<>();
        //发货 找物流
        fragments.add(SelectAddressFragment.newInstance());
        fragments.add(SearchLogisticsFragment.newInstance());

        mViewPage.setOffscreenPageLimit(fragments.size());
        mViewPage.setAdapter(new FragmentAdapter(activity, fragments));
        new TabLayoutMediator(mTabLayout, mViewPage, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(position == 0 ? "发货" : "找物流");
            }
        }).attach();

        mViewPage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                updatePagerHeightForChild(fragments.get(position).getView(), mViewPage);
            }
        });

        Map<String, String> map = new ArrayMap<>();
        map.put("platform", "cargo");
        map.put("city", "1");
        map.put("ad_sign", "AppCargoHome");//AppLogisticsManage
        networkRequest(netApi.get_ad_list(map), this, 9527);
        if (EasyPermissions.hasPermissions(getContext(), locationUtils.perms)) {
            locationUtils.methodRequiresTwoPermission(getActivity(), this);
        }
        city = SharedPreferencesUtils.getString(getContext(), "city");
        if (!TextUtils.isEmpty(city)) {
            mTvCity.setText(city);
        }
        if (Constants.isFirst) {
            networkRequest(netApi.receive_redpack(Constants.city), this, 88);
        } else {
            networkRequest(netApi.regCouponList(), this, 108);
        }

        networkRequest(netApi.get_user_info(), this, 99);
    }


    //计算fragment的高度并设置给viewPager
    private void updatePagerHeightForChild(View view, ViewPager2 pager) {
        if (view != null && view.getWidth() > 0) {
            int wMeasureSpec = View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY);
            int hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(wMeasureSpec, hMeasureSpec);
            if (pager.getLayoutParams().height != view.getMeasuredHeight()) {
                pager.getLayoutParams().height = view.getMeasuredHeight();
            }
        }
    }

    private final ActivityResultLauncher<ScanOptions> barcodeLauncher = registerForActivityResult(new ScanContract(), result -> {
        if (result.getContents() == null) {
            //Toast.makeText(ScanCodeDeliveryActivity.this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            String contents=result.getContents();
            LogUtils.d(contents);
            if (contents.contains("order?")) {
                String value = MyUtils.readValueFromUrlStrByParamName(result.getContents(), "logistics_id");
                startActivity(new Intent(getContext(), DispatchAndCollectActivity.class).putExtra("logistics_id", Integer.parseInt(value)));
            }else if(contents.contains("track")){
                String deliver_sn=MyUtils.readValueFromUrlStrByParamName(contents,"deliver_sn");
                startActivity(new Intent(getContext(), LogisticsTrackActivity.class)
                        .putExtra("deliver_sn",deliver_sn));
            }else if(contents.contains("company")){
                String logistics_id=MyUtils.readValueFromUrlStrByParamName(contents,"logistics_id");
                startActivity(new Intent(getContext(), CompanyDetailsActivity.class)
                        .putExtra("logistics_id",Integer.parseInt(logistics_id)));
            }
        }
    });

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_city:
                selectCity();
                break;
            case R.id.fl_search:
                startActivity(new Intent(getContext(), OrderSearchActivity.class));
                break;
            case R.id.fl_scan:
                ScanOptions options = new ScanOptions();
                options.setDesiredBarcodeFormats(ScanOptions.QR_CODE);
                options.setOrientationLocked(false);
                options.setPrompt("请将二维码置于取景框内扫描");
                barcodeLauncher.launch(options);
                break;
        }
    }

    private void selectCity() {
        CityPicker.from(this).setLocatedCity(null).setOnPickListener(new OnPickListener() {
            @Override
            public void onPick(int position, City data) {
                mTvCity.setText(data.getName());
                SharedPreferencesUtils.saveString(getContext(), "city", data.getName());
            }

            @Override
            public void onCancel() {
                LogUtils.d("取消选择");
            }

            @Override
            public void onLocate() {
                if (TextUtils.isEmpty(Constants.city)) {
                    locationUtils.methodRequiresTwoPermission(getActivity(), null);
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            CityPicker.from(SanSongFragment.this).locateComplete(new LocatedCity(Constants.city, Constants.province, Constants.cityCode), LocateState.SUCCESS);
                        }
                    }, 500);
                }
            }
        }).show();
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 9527) {
            AdvertisingBean infoBean = new Gson().fromJson(json, AdvertisingBean.class);
            if (infoBean.isStatus() && !MyUtils.isEmpty(infoBean.getData().getList())) {
                ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(infoBean.getData().getList(), getContext(),1,true);
                mVpCarousel.setAdapter(pagerAdapter);
                mIndicator.setUpWidthViewPager(mVpCarousel, infoBean.getData().getList().size());
            }
        } else if (requestCode == 88) {
            AdvancePayment bean = new Gson().fromJson(json, AdvancePayment.class);
            if (bean.isStatus()) {
                new RedPacketDialog(getContext(), bean.getData().getRedpack()).show();
            }
        } else if (requestCode == 99) {
            UserInfo userInfo = new Gson().fromJson(json, UserInfo.class);
            if (userInfo.isStatus()) {
                EventBus.getDefault().postSticky(userInfo);
            }
        } else if (requestCode == 108) {
            ActivityBean bean = new Gson().fromJson(json, ActivityBean.class);
            if (bean.getCode().equals("1") && bean.getData().size() > 0) {
                DiscountCouponDialog discountCouponDialog = new DiscountCouponDialog(getContext(), bean.getData(), "新人福利");
                discountCouponDialog.show();
                discountCouponDialog.setMyClickListener(new MyClickListener2() {
                    @Override
                    public void onClick(String id, String info) {
                        networkRequest(netApi.regCouponUnshow(id), null);
                    }
                });
            } else {
                networkRequest(netApi.promotionCouponList(), this, 109);
            }
        } else if (requestCode == 109) {
            CouponSearchBean bean = new Gson().fromJson(json, CouponSearchBean.class);
            if (bean.getCode().equals("1") && bean.getData().getList().size() > 0) {
                DiscountCouponDialog discountCouponDialog = new DiscountCouponDialog(getContext(), bean.getData().getList(), "优惠券派送");
                discountCouponDialog.show();
                discountCouponDialog.setMyClickListener(new MyClickListener2() {
                    @Override
                    public void onClick(String id, String info) {
                        if (!TextUtils.isEmpty(info)) {
                            networkRequest(netApi.getPromotionCoupon(), null);
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onResumes() {
        super.onResumes();
        if (mVpCarousel != null) {
            mVpCarousel.startAutoPlay();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mVpCarousel != null) {
            mVpCarousel.stopAutoPlay();
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Subscribe
    public void onEvent(Permission event) {
        locationUtils.methodRequiresTwoPermission(getActivity(), this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        CityPicker.from(SanSongFragment.this).locateComplete(new LocatedCity(aMapLocation.getCity(), aMapLocation.getProvince(), aMapLocation.getCityCode()), LocateState.SUCCESS);
        Constants.latitude = aMapLocation.getLatitude();
        Constants.longitude = aMapLocation.getLongitude();
        Constants.city = aMapLocation.getCity();
        Constants.province = aMapLocation.getProvince();
        Constants.cityCode = aMapLocation.getCityCode();
        if (!TextUtils.isEmpty(city)) {
            mTvCity.setText(aMapLocation.getCity());
        }
    }
}